package com.tianwu.lbsdatabasedesign;


import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity {

    private MapView mMapView;
    private BaiduMap mBaiduMap;
    private Handler mHandler;

    private TextView log;
    private String logMessage;

    private static final int TIME_INTERVAL = 10000;

    private List<LatLng> polylines;

    private SaveLocation saveLocation;

    private LocationClient locationClient;

    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;

        stopTraceServer();

        log = (TextView) findViewById(R.id.logText);
        logMessage = log.getText().toString() + "\n";

        polylines = new ArrayList<>();

        mMapView = (MapView) findViewById(R.id.bmapView);
        mMapView.onCreate(this, savedInstanceState);
        mBaiduMap = mMapView.getMap();
        mBaiduMap.setMyLocationEnabled(true);

        // 设置定位图层的配置（定位模式，是否允许方向信息，用户自定义定位图标）
        MyLocationConfiguration config =
                new MyLocationConfiguration(MyLocationConfiguration.LocationMode.FOLLOWING,
                        true, BitmapDescriptorFactory.fromResource(R.drawable.zuobiao));
        mBaiduMap.setMyLocationConfigeration(config);

        locationClient = new LocationClient(this);
        settingLocationClicent(TIME_INTERVAL);
        initLocationClicent();

        mHandler = new Handler(Looper.getMainLooper());
        looper();

        locationClient.start();
    }
    private void initTraceMarker(){
        polylines.clear();
        for(MyLocation ml : SaveLocation.getAllLocation(this.getApplicationContext()))
            polylines.add(new LatLng(ml.latitude,ml.longitude));
        if(polylines.size() >= 2) {
            OverlayOptions palylineOptions = new PolylineOptions().points(polylines).width(10).color(Color.RED);
            mBaiduMap.addOverlay(palylineOptions);
        }
    }

    public void startTraceServer(){
        Intent server = new Intent(this,TraceLocationService.class);
        server.putExtra("span", TIME_INTERVAL);
        startService(server);
    }
    public void stopTraceServer(){
        Intent server = new Intent(this,TraceLocationService.class);
        stopService(server);
    }
    private void settingLocationClicent(int span){
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");
        //可选，默认gcj02，设置返回的定位结果坐标系
        option.setScanSpan(span);
        //可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);
        //可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);
        //可选，默认false,设置是否使用gps
        option.setLocationNotify(true);
        //可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);
        //可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);
        //可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);
        //可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);
        //可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);
        //可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        locationClient.setLocOption(option);
    }
    private void initLocationClicent(){
        locationClient.registerLocationListener(new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {
                SaveLocation.addLocation(context,new MyLocation(bdLocation.getTime(),
                        bdLocation.getAddrStr(),
                        bdLocation.getLatitude(),
                        bdLocation.getLongitude()));

                mBaiduMap.setMyLocationData(new MyLocationData.Builder()
                        .accuracy(bdLocation.getRadius())
                        .direction(bdLocation.getDirection())
                        .latitude(bdLocation.getLatitude())
                        .longitude(bdLocation.getLongitude())
                        .build());
                logMessage += bdLocation.getAddrStr() + "\n";
                log.setText(logMessage);
            }
        });
    }
    public void looper(){
        new Thread(){
            public void run(){
                while(true){
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            initTraceMarker();
                            logMessage += polylines.size() + "\n";
                            log.setText(logMessage);
                        }
                    });
                    try {
                        Thread.sleep(TIME_INTERVAL);
                    } catch (InterruptedException e) {
                        logMessage += e.getMessage() + "\n";
                        log.setText(logMessage);
                    }
                }
            }
        }.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
        mBaiduMap.clear();
        startTraceServer();
    }
    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }
}
